package me.flyray.bsin.gateway.portal;


import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import me.flyray.bsin.utils.BsinServiceInvokeUtil;

@Slf4j
@RestController
@RequestMapping("/notify")
public class BsinNotifyPortal {

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private BsinServiceInvokeUtil bsinServiceInvokeUtil;

    @RequestMapping("/erp/stock")
    @Transactional(rollbackFor = Exception.class)
    public Object stock(@RequestBody String body) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(body);
        String ciphertext = jsonObject.getString("ciphertext");
        // 验签

        return "ok";
    }

    @RequestMapping("/wxpay")
    @Transactional(rollbackFor = Exception.class)
    public Object wxpay(@RequestBody String body) throws Exception {
        WxPayOrderNotifyResult result = null;
        try {
            result = wxPayService.parseOrderNotifyResult(body);
            log.info("处理腾讯支付平台的订单支付");
            log.info(JSONObject.toJSONString(result));
            // 处理微信支付成功回调
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("resultCode", result.getResultCode());
            requestMap.put("tradeNo", result.getOutTradeNo());
            requestMap.put("cashFee", result.getCashFee());
            requestMap.put("payId", result.getTransactionId());
            // 根据订单号请求回调 "pn-"开头是购买nft订单 rn-开头是充值订单
            String[] strs = result.getOutTradeNo().split("-");//根据，切分字符串
            Map map = new HashMap<>();
            if ("pn".equals(strs[0])) {
                map = bsinServiceInvokeUtil.genericInvoke("NftGoodsService", "buyNft", requestMap);
                return map.get("data");
            } else if ("rn".equals(strs[0])) {
                map = bsinServiceInvokeUtil.genericInvoke("AdminRechargeOrderService", "rechargeInAccount", requestMap);
            }
            return map.get("data");

        } catch (WxPayException we) {
            log.error("[微信解析回调请求] 异常", we);
            return WxPayNotifyResponse.fail(we.getMessage());
        } catch (Exception e) {
            return WxPayNotifyResponse.fail("支付失败");
        }
    }

}


